package com.beiing.tianshuai.tianshuai.dongtai.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.DynamicComment_RVAdapter;
import com.beiing.tianshuai.tianshuai.anim.LikeAnimator;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.dongtai.CommentReplyActivity;
import com.beiing.tianshuai.tianshuai.dongtai.DynamicForwardActivity;
import com.beiing.tianshuai.tianshuai.dongtai.PraiseDetailActivity;
import com.beiing.tianshuai.tianshuai.dongtai.presenter.DynamicDetailPresenter;
import com.beiing.tianshuai.tianshuai.entity.DynamicBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicCommentBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicDeleteBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicDetailBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicPraiseBean;
import com.beiing.tianshuai.tianshuai.entity.FollowBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SpanStringUtils;
import com.beiing.tianshuai.tianshuai.widget.ActionSheet;
import com.beiing.tianshuai.tianshuai.widget.ApproveListLayout;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.bumptech.glide.Glide;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 动态详情界面
 *
 * @author 刘泽启
 * @date 2017/8/2
 */

public class DynamicDetailActivity extends BaseActivity implements DynamicDetailViewImpl {

    public static String TAG = "DynamicDetailActivity";

    private String uid;
    private String cid;
    private String toUid;
    private String publisherId;

    /**
     * 列表页获取到的动态id
     */
    private String mDynamicId;
    private DynamicBean.DataBean.DynamicsBean dynamic;
    private DynamicDetailBean.DataBean dynamicDetail;
    private List<DynamicDetailBean.DataBean.UserThingBean> userThingBeanList;

    /**
     * 当前用户点赞实体
     */
    private DynamicDetailBean.DataBean.UserThingBean mUserThingBean;
    private List<DynamicDetailBean.DataBean.CommentBean> commentBeanList;
    private DynamicComment_RVAdapter mAdapter;
    private DynamicDetailPresenter mPresenter;
    private InputMethodManager imm;
    private Drawable attention;
    private int mPosition;
    private int dynamicPosition;
    private AlphaAnimation mHideAnimation;
    private boolean isFirstLoad = true;
    private Drawable drawableLike;

    private boolean emotionLayoutShow;

    /**
     * 评论列表排序菜单
     */
    private EasyPopup mPopup;

    /**
     * 评论排序方式
     */
    private int type = 0;

    /**
     * 第几页
     */
    private int page = 1;

    /**
     * 每页有多少条数据
     */
    private int num = 20;

    /**
     * 是否是上拉加载更多
     */
    private boolean isLoadMore;

    /**
     * 点赞头像集合
     */
    private List<String> thingPhotoList;

    /**
     * 圆形头像
     */
    @BindView(R.id.title_head)
    CircleImageView civTitleHead;

    /**
     * 用户名
     */
    @BindView(R.id.dynamic_detail_name)
    TextView tvName;

    /**
     * 用户所在院校
     */
    @BindView(R.id.dynamic_detail_unit)
    TextView tvUnit;

    /**
     * 关注
     */
    @BindView(R.id.dynamic_detail_attention)
    TextView tvAttention;

    /**
     * 动态文字内容
     */
    @BindView(R.id.dynamic_detail_content)
    TextView tvContent;

    /**
     * 动态图片内容
     */
    @BindView(R.id.dynamic_detail_ninegridview)
    NineGridView mNineGridView;

    /**
     * 时间
     */
    @BindView(R.id.dynamic_detail_time)
    TextView tvTime;

    /**
     * 点赞-数量
     */
    @BindView(R.id.dynamic_detail_praise)
    TextView tvPraise;

    /**
     * 评论-数量
     */
    @BindView(R.id.dynamic_detail_comment)
    TextView tvComment;

    /**
     * 转发-数量
     */
    @BindView(R.id.dynamic_detail_forward)
    TextView tvForward;

    /**
     * 动态评论输入框
     */
    @BindView(R.id.dynamic_detail_edit)
    EditText mEditComment;

    /**
     * 发送评论
     */
    @BindView(R.id.dynamic_detail_send)
    TextView mSend;

    /**
     * 评论总条数
     */
    @BindView(R.id.dynamic_detail_comment_num)
    TextView mCommentNum;

    /**
     * 评论列表
     */
    @BindView(R.id.view_loading)
    View mLoadingBackground;

    @BindView(R.id.dynamic_detail_recycler)
    RecyclerView mRecyclerView;

    /**
     * +1文字动画
     */
    @BindView(R.id.iv_face)
    ImageView ivFace;

    @BindView(R.id.tv_add_one)
    TextView mTvAddOne;

    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;

    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;

    @BindView(R.id.btn_order_by)
    ImageButton mBtnOrderBy;

    @BindView(R.id.rl_container)
    RelativeLayout rlContainer;

    @BindView(R.id.smtRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.refresh_header)
    MyRefreshHeader refreshHeader;

    @BindView(R.id.refresh_footer)
    RefreshFooter refreshFooter;

    @BindView(R.id.approve_list)
    ApproveListLayout approveList;

    @BindView(R.id.tv_approve_num)
    TextView tvApproveNum;

    @BindView(R.id.ll_approve)
    LinearLayout llApprove;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamic_detail;
    }

    @Override
    protected void init() {
        CustomProgressDialog.showLoading(mContext, "", true);
        CustomProgressDialog.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        initData();
        initRefreshLayout();
        initRecyclerView();
        setPresenter();
        setListener();
        initEmotionMainFragment();
        mPopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_dynamic_comment_order_by)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();
    }

    private void initEmotionMainFragment() {
        //表情面板是否显示
        GlobalOnItemClickManagerUtils globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManager.attachToEditText(mEditComment);
        EmotionCompleteFragment emotionCompleteFragment = new EmotionCompleteFragment();
        try {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setPresenter() {
        mPresenter = new DynamicDetailPresenter(this);
        //获取动态详情
        mPresenter.getDynamicDetail(uid, mDynamicId, type, page, num, isLoadMore);
    }

    /**
     * 上拉加载与下拉刷新
     */
    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                isLoadMore = false;
                isFirstLoad = true;
                mPresenter.getDynamicDetail(uid, mDynamicId, type, page, num, false);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isLoadMore = true;
                mPresenter.getDynamicDetail(uid, mDynamicId, type, page, num, true);
            }
        });
    }

    /**
     * 初始化RecyclerView,以及设置其点击事件
     */
    private void initRecyclerView() {
        commentBeanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setNestedScrollingEnabled(false);
        //避免notifyItemChanged造成的闪烁
        mRecyclerView.getItemAnimator().setChangeDuration(0);
        mAdapter = new DynamicComment_RVAdapter(mContext, commentBeanList);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemViewClickListener(new DynamicComment_RVAdapter.OnItemViewClickListener() {
            @Override
            public void onItemViewClick(View view, int position) {
                final String uid = commentBeanList.get(position).getUid();
                switch (view.getId()) {
                    case R.id.dynamic_comment_ll_head:
                        //查看评论个人信息
                        mAdapter.setOnItemClickListener(null);
                        if (!TextUtils.isEmpty(uid)) {
                            Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                            intent.putExtra("uid", uid);
                            startActivity(intent);
                        }
                        break;
                    case R.id.dynamic_comment_praise:
                        //评论点赞
                        mAdapter.setOnItemClickListener(null);
                        if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                            startActivity(new Intent(mContext, LoginActivity.class));
                        } else {
                            mPresenter.praiseComment(DynamicDetailActivity.this.uid, commentBeanList.get(position).getId(), uid, mDynamicId, position);
                        }
                        break;
                    default:
                        mAdapter.setOnItemClickListener(new DynamicComment_RVAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                view.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
                                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                                    startActivity(new Intent(mContext, LoginActivity.class));
                                } else {
                                    if (commentBeanList.get(position).getUid().equals(UserInfoBean.getUid(mContext))) {
                                        showPopupMenu(view, position, commentBeanList.get(position));
                                    } else {
                                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                                        mEditComment.setFocusable(true);
                                        mEditComment.setFocusableInTouchMode(true);
                                        mEditComment.requestFocus();
                                        mEditComment.setHint("回复" + commentBeanList.get(position).getName());
                                        cid = commentBeanList.get(position).getId();
                                        toUid = commentBeanList.get(position).getUid();
                                    }
                                }
                            }
                        });
                }
            }
        });

        mAdapter.setOnMoreClickListener(new DynamicComment_RVAdapter.OnMoreClickListener() {
            @Override
            public void onMoreClick(View view, int position, DynamicDetailBean.DataBean.CommentBean bean) {
                cid = commentBeanList.get(position).getId();
                showDynamicMenu(mContext, position, bean);
                isFinishing();
            }
        });

        mAdapter.setOnTextClickListener(new DynamicComment_RVAdapter.OnTextClickListener() {
            @Override
            public void onTextClick(View view, final int position, final int childPosition, int textPosition) {
                switch (textPosition) {
                    case 1:
                        String formUid = commentBeanList.get(position).getReply().get(childPosition).getFormUid();
                        if (!TextUtils.isEmpty(formUid)) {
                            Intent intent = new Intent();
                            intent.setClass(mContext, NewPersonalIndexActivity.class);
                            intent.putExtra("uid", formUid);
                            mContext.startActivity(intent);
                        }
                        break;
                    case 2:
                        String toUid = commentBeanList.get(position).getReply().get(childPosition).getToUid();
                        if (!TextUtils.isEmpty(toUid)) {
                            Intent intent1 = new Intent();
                            intent1.setClass(mContext, NewPersonalIndexActivity.class);
                            intent1.putExtra("uid", toUid);
                            mContext.startActivity(intent1);
                        }
                        break;
                    default:
                }
            }
        });

        mAdapter.setOnChildItemClickListener(new DynamicComment_RVAdapter.OnChildItemClickListener() {
            @Override
            public void onChildItemClick(View view, int position, int childPosition) {
                Intent intent = new Intent();
                intent.setClass(mContext, CommentReplyActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("reply", commentBeanList.get(position));
                intent.putExtra("position", position);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    /**
     * 若是自己发布的评论，点击弹出删除菜单
     */
    private void showPopupMenu(View view, final int position, final DynamicDetailBean.DataBean.CommentBean commentBean) {
        PopupMenu popupMenu = new PopupMenu(mContext, view, Gravity.END);
        popupMenu.getMenuInflater().inflate(R.menu.comment_click_menu, popupMenu.getMenu());
        popupMenu.getMenu().findItem(R.id.item_copy).setVisible(false);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.item_delete:
                        mPresenter.deleteComment(uid, commentBean.getId(), mDynamicId, position, dynamicPosition);
                        break;
                    default:
                }
                return false;
            }
        });
        popupMenu.show();
    }

    /**
     * 1.拿到由列表页传递过来的网络请求所需参数
     * 2.一些初始化操作
     */
    private void initData() {
        Intent intent = this.getIntent();
        mDynamicId = intent.getStringExtra("dynamic_id");
        dynamicPosition = intent.getIntExtra("dynamic_position", -1);
        dynamic = (DynamicBean.DataBean.DynamicsBean) intent.getSerializableExtra("dynamic");

        //点击动态列表中评论按钮按钮过来时弹出输入框
        final String comment = "comment";
        if (intent.getStringExtra(comment) != null) {
            mEditComment.setFocusable(true);
            mEditComment.setFocusableInTouchMode(true);
            mEditComment.requestFocus();
        }
        uid = UserInfoBean.getUid(mContext);

        attention = getResources().getDrawable(R.drawable.icon_add_32);
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        drawableLike = ContextCompat.getDrawable(mContext, R.drawable.ic_dynamic_praise_red);

        mUserThingBean = new DynamicDetailBean.DataBean.UserThingBean();
        mUserThingBean.setId(UserInfoBean.getUid(mContext));
        mUserThingBean.setName(UserInfoBean.getNickName(mContext));
        mUserThingBean.setPhoto(UserInfoBean.getAvatar(mContext));
    }

    /**
     * 显示动态详情
     *
     * @param dynamicDetailBean 动态实体数据
     */
    @Override
    public void showDynamicDetail(DynamicDetailBean dynamicDetailBean) {
        dynamicDetail = dynamicDetailBean.getData();
        userThingBeanList = dynamicDetail.getUserThing();
        thingPhotoList = new ArrayList<>();
        if (userThingBeanList != null && userThingBeanList.size() > 0) {
            for (int i = 0; i < userThingBeanList.size(); i++) {
                thingPhotoList.add(userThingBeanList.get(i).getPhoto());
            }
            llApprove.setVisibility(View.VISIBLE);
            tvApproveNum.setText(userThingBeanList.size() > 13 ? "+" + String.valueOf(userThingBeanList.size()) + "人赞" : String.valueOf(userThingBeanList.size() + "人赞"));
        }
        approveList.updateApproveList(thingPhotoList);
        approveList.setOnHeaderClickListener(new ApproveListLayout.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(View view, int position) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", userThingBeanList.get(12 - position).getId());
                startActivity(intent);
            }
        });

        Glide.with(getApplicationContext())
                .load(TextUtils.isEmpty(dynamicDetail.getPhoto()) ? R.mipmap.default_avatar
                        : HttpRequestConstant.USER_PIC_HEAD + dynamicDetail.getPhoto())
                .into(civTitleHead);
        tvName.setText(dynamicDetail.getName());
        tvUnit.setText(dynamicDetail.getUnit());
        if ("".equals(dynamicDetail.getContent())) {
            tvContent.setVisibility(View.GONE);
        } else {
            String decodeContent = null;
            try {
                decodeContent = URLDecoder.decode(dynamicDetail.getContent() == null ? "" : dynamicDetail.getContent(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            tvContent.setText(SpanStringUtils.getEmotionContent(mContext, tvContent, decodeContent));
        }
        if (dynamicDetail.getIsThing() == 1) {
            if (isFirstLoad) {
                isFirstLoad = false;
                drawableLike.setBounds(0, 0, drawableLike.getMinimumWidth(), drawableLike.getMinimumHeight());
                tvPraise.setCompoundDrawables(drawableLike, null, null, null);
            } else {
                LikeAnimator.thumbAnimator(mContext, tvPraise);
                LikeAnimator.addOneTextAnimator(mContext, mTvAddOne);
            }
        } else {
            if (isFirstLoad) {
                isFirstLoad = false;
            }
            LikeAnimator.disLikeAnimator(mContext, tvPraise);
        }
        tvForward.setText(dynamicDetail.getRelay());
        tvPraise.setText(MessageFormat.format("{0}", dynamicDetail.getThing()));
        List<DynamicDetailBean.DataBean.PicnameBean> pic = dynamicDetail.getPicname();
        if (pic != null && pic.size() > 0) {
            mNineGridView.setVisibility(View.VISIBLE);
            ArrayList<ImageInfo> imageInfos = new ArrayList<>();
            for (DynamicDetailBean.DataBean.PicnameBean picBean : pic) {
                String url = HttpRequestConstant.DYNAMIC_PIC_HEAD + picBean.getPicname();
//                String thumbUrl = HttpRequestConstant.DYNAMIC_PIC_THUMBNAIL + picBean.getPicname();
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.setThumbnailUrl(url);
                imageInfo.setBigImageUrl(url);
                imageInfo.setImageViewHeight(Integer.parseInt(picBean.getHeight()));
                imageInfo.setImageViewWidth(Integer.parseInt(picBean.getWidth()));
                imageInfo.setImageHeight(Integer.parseInt(picBean.getHeight()));
                imageInfo.setImageWidth(Integer.parseInt(picBean.getWidth()));
                imageInfos.add(imageInfo);
            }
            mNineGridView.setAdapter(new NineGridViewClickAdapter(mContext, imageInfos));
        } else {
            mNineGridView.setVisibility(View.GONE);
        }

        publisherId = dynamicDetail.getUid();
        //获取关注状态
        mPresenter.isFollowed(uid, publisherId);
        toUid = dynamicDetail.getUid();

        tvTime.setText(DateUtil.timeStamp2Date(dynamicDetail.getTime(), "MM-dd HH:mm"));

        tvComment.setText(MessageFormat.format("{0}", dynamicDetail.getDynamic_comment()));
        if (uid.equals(dynamicDetail.getUid())) {
            tvAttention.setVisibility(View.GONE);
        }
        mCommentNum.setText(MessageFormat.format("评论{0}", dynamicDetail.getDynamic_comment()));

        List<DynamicDetailBean.DataBean.CommentBean> commentBeen = dynamicDetail.getComment();
        commentBeanList.clear();
        commentBeanList.addAll(commentBeen);
        page++;
        mAdapter.notifyDataSetChanged();
        if (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading()) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void loadMoreComment(List<DynamicDetailBean.DataBean.CommentBean> commentBeanList) {
        page++;
        mAdapter.notifyDataSetChanged();
        if (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading()) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadmore();
        }
    }

    @OnClick({R.id.title_iv_back, R.id.dynamic_detail_attention, R.id.dynamic_detail_praise,
            R.id.dynamic_detail_comment, R.id.dynamic_detail_forward, R.id.dynamic_detail_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_iv_back:
                //toolbar返回
                finish();
                break;
            case R.id.dynamic_detail_attention:
                //关注
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    //关注用户
                    mPresenter.setFollowed(uid, publisherId);
                }
                break;
            case R.id.dynamic_detail_praise:
                //动态点赞
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.praiseDynamic(uid, mDynamicId, publisherId, dynamicPosition);
                }
                break;
            case R.id.dynamic_detail_comment:
                //评论
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    if (emotionLayoutShow) {
                        mEmotionLayout.setVisibility(View.GONE);
                        emotionLayoutShow = false;
                    }
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    mEditComment.setFocusable(true);
                    mEditComment.setFocusableInTouchMode(true);
                    mEditComment.requestFocus();
                }
                break;
            case R.id.dynamic_detail_forward:
                //转发
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    Intent forwardIntent = new Intent();
                    forwardIntent.setClass(mContext, DynamicForwardActivity.class);
                    Bundle forwardBundle = new Bundle();
                    forwardBundle.putSerializable("dynamic", dynamic);
                    forwardIntent.putExtras(forwardBundle);
                    startActivity(forwardIntent);
                }
                break;
            case R.id.dynamic_detail_send:
                //发送评论
                if (!TextUtils.isEmpty(mEditComment.getText().toString().trim())) {
                    if ("说几句...".contentEquals(mEditComment.getHint())) {
                        //评论
                        LogUtils.i(publisherId, "评论点击");
                        String content = mEditComment.getText().toString().trim();
                        String contentUTF8 = null;
                        try {
                            contentUTF8 = URLEncoder.encode(content, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        isFirstLoad = true;
                        mPresenter.addComment(uid, publisherId, mDynamicId, contentUTF8, publisherId, System.currentTimeMillis() / 1000 + "", dynamicPosition);
                    } else {                                                    //回复
                        String content = mEditComment.getText().toString().trim();
                        String contentUTF8 = null;
                        try {
                            contentUTF8 = URLEncoder.encode(content, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        isFirstLoad = true;
                        mPresenter.addReply(mDynamicId, cid, uid, toUid, contentUTF8, toUid);
                    }
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                    mEmotionLayout.setVisibility(View.GONE);
                    mEditComment.clearFocus();
                    mEditComment.setText("");
                }
                break;
            default:
        }
    }

    /**
     * 事件监听
     */
    @SuppressLint("ClickableViewAccessibility")
    private void setListener() {

        CustomProgressDialog.setListener(new CustomProgressDialog.OnDismiss() {
            @Override
            public void onDismissListener() {
                setHideAnimation(mLoadingBackground, 888);
            }
        });

        mBtnOrderBy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopupWindow();
                int i = v.getLayoutParams().width / 2 + DensityUtils.dp2px(mContext, 6);
                mPopup.showAtAnchorView(v, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 9));
            }
        });

        rlContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEditComment.setFocusable(false);
                mEditComment.setHint("说几句...");
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.GONE);
                emotionLayoutShow = false;
                return false;
            }
        });

        //输入框点击监听
        mEditComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mEditComment.setFocusable(true);
                    mEditComment.setFocusableInTouchMode(true);
                    mEditComment.requestFocus();
                    mEmotionLayout.setVisibility(View.GONE);
                    ivKeyBoard.setVisibility(View.GONE);
                    ivFace.setVisibility(View.VISIBLE);
                    emotionLayoutShow = false;
                }
                return false;
            }
        });

        mSend.setClickable(false);
        //输入框输入监听
        mEditComment.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && !"".equals(s.toString().trim())) {
                    //有文字内容
                    mSend.setBackgroundResource(R.drawable.publish_blue);
                    mSend.setClickable(true);
                } else {
                    mSend.setBackgroundResource(R.drawable.publish_gray);
                    //没有文字内容
                    mSend.setClickable(false);
                }
            }
        });

        civTitleHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(publisherId)) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", publisherId);
                    startActivity(intent);
                }
            }
        });

        llApprove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, PraiseDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("dynamicDetail", dynamicDetail);
                intent.putExtra("from_activity", "dynamic");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!emotionLayoutShow) {
                    ivFace.setVisibility(View.GONE);
                    ivKeyBoard.setVisibility(View.VISIBLE);
                    emotionLayoutShow = true;
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                    mEmotionLayout.setVisibility(View.VISIBLE);
                }

            }
        });

        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                emotionLayoutShow = false;
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mEditComment.setFocusable(true);
                mEditComment.setFocusableInTouchMode(true);
                mEditComment.requestFocus();
            }
        });
    }

    private void initPopupWindow() {
        // 最热
        TextView tvOrderByHot = mPopup.getView(R.id.action_order_by_hot);
        // 最新
        TextView tvOrderByNew = mPopup.getView(R.id.action_order_by_new);
        // 最先
        TextView tvOrderByOld = mPopup.getView(R.id.action_order_by_old);

        // 设置按热度排序点击事件
        tvOrderByHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                type = 2;
                isLoadMore = false;
                isFirstLoad = true;
                //获取动态详情
                mPresenter.getDynamicDetail(uid, mDynamicId, type, page, num, isLoadMore);
                mPopup.dismiss();
            }
        });

        tvOrderByNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                page = 1;
                type = 0;
                isLoadMore = false;
                isFirstLoad = true;
                mPresenter.getDynamicDetail(uid, mDynamicId, type, page, num, isLoadMore);
                mPopup.dismiss();
            }
        });

        // 设置按时间排序点击事件
        tvOrderByOld.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                type = 1;
                isLoadMore = false;
                isFirstLoad = true;
                mPresenter.getDynamicDetail(uid, mDynamicId, type, page, num, isLoadMore);
                mPopup.dismiss();
            }
        });

    }


    @Override
    public void onBackPressed() {
        if (emotionLayoutShow) {
            mEmotionLayout.setVisibility(View.GONE);
            emotionLayoutShow = false;
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 进入加载层消失动画
     *
     * @param view
     * @param duration
     */
    private void setHideAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }
        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }

        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(mHideAnimation);
    }

    /**
     * 添加评论
     *
     * @param bean
     */
    @Override
    public void refreshComment(DynamicCommentBean bean) {
        DynamicDetailBean.DataBean.CommentBean commentBean = new DynamicDetailBean.DataBean.CommentBean();
        commentBean.setContent(bean.getData().getContent());
        commentBean.setCreate_time(System.currentTimeMillis() / 1000 + "");
        commentBean.setUid(uid);
        commentBean.setId(bean.getData().getId());
        commentBean.setPhoto(UserInfoBean.getAvatar(mContext));
        commentBean.setName(UserInfoBean.getNickName(mContext));
        commentBean.setUnit(UserInfoBean.getUniversity(mContext));
        commentBean.setThing("0");
        commentBean.setIs_thing(0);
        commentBeanList.add(0, commentBean);
        mAdapter.notifyDataSetChanged();
        tvComment.setText(String.valueOf(bean.getData().getCount()));
        mCommentNum.setText(MessageFormat.format("评论{0}", bean.getData().getCount()));
    }

    @Override
    public void showToast(String msg) {
        showShortText(msg);
    }

    /**
     * 删除评论
     *
     * @param deleteBean
     * @param position
     */
    @Override
    public void deleteComment(DynamicDeleteBean deleteBean, int position) {
        if (deleteBean.getCode() == 200) {
            commentBeanList.remove(position);
            mAdapter.notifyDataSetChanged();
            tvComment.setText(String.valueOf(deleteBean.getData().getCount()));
            mCommentNum.setText(MessageFormat.format("全部{0}条评论", deleteBean.getData().getCount()));
            showShortText("删除成功");
        } else {
            LogUtils.e("删除失败" + deleteBean.getCode(), TAG);
            showShortText("删除失败，请重试");
        }
    }

    /**
     * 移除评论的回复
     *
     * @param position
     * @param childPosition
     */
    @Override
    public void deleteReply(int position, int childPosition) {
        mAdapter.removeChildItem(position, childPosition);
    }

    @Override
    public void showError(String error) {
        showShortText(error);
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void showCommentPraiseResult(DynamicPraiseBean praiseBean, int commentPosition) {
        commentBeanList.get(commentPosition).setThing(praiseBean.getData().getCount() + "");
        if (praiseBean.getCode() == 200) {
            commentBeanList.get(commentPosition).setIs_thing(1);
        } else if (praiseBean.getCode() == 201) {
            commentBeanList.get(commentPosition).setIs_thing(0);
        }
        mAdapter.notifyItemChanged(commentPosition);
    }

    /**
     * 动态点赞结果
     *
     * @param praiseBean
     */
    @Override
    public void showDynamicPraiseResult(DynamicPraiseBean praiseBean) {
        if (praiseBean.getCode() == 200) {
            //点赞成功
            LikeAnimator.thumbAnimator(mContext, tvPraise);
            LikeAnimator.addOneTextAnimator(mContext, mTvAddOne);
            tvPraise.setText(MessageFormat.format("{0}", praiseBean.getData().getCount()));
            if (userThingBeanList == null) {
                userThingBeanList = new ArrayList<>();
            }
            userThingBeanList.add(0, mUserThingBean);
            thingPhotoList.add(0, UserInfoBean.getAvatar(mContext));
            llApprove.setVisibility(View.VISIBLE);
            tvApproveNum.setText(userThingBeanList.size() > 13 ? "+" + String.valueOf(userThingBeanList.size()) + "人赞" : String.valueOf(userThingBeanList.size() + "人赞"));
            approveList.updateApproveList(thingPhotoList);
        } else if (praiseBean.getCode() == 201) {
            //取消点赞成功
            LikeAnimator.disLikeAnimator(mContext, tvPraise);
            tvPraise.setText(MessageFormat.format("{0}", praiseBean.getData().getCount()));
            DynamicDetailBean.DataBean.UserThingBean userThingBeanDel = new DynamicDetailBean.DataBean.UserThingBean();
            for (DynamicDetailBean.DataBean.UserThingBean userThingBean : userThingBeanList) {
                if (TextUtils.equals(userThingBean.getId(), UserInfoBean.getUid(mContext))) {
                    userThingBeanDel = userThingBean;
                }
            }
            userThingBeanList.remove(userThingBeanDel);
            String deleteUrl = null;
            for (String url : thingPhotoList) {
                if (TextUtils.equals(url, UserInfoBean.getAvatar(mContext))) {
                    deleteUrl = url;
                }
            }
            thingPhotoList.remove(deleteUrl);
            if (thingPhotoList.size() == 0) {
                llApprove.setVisibility(View.GONE);
            }
            tvApproveNum.setText(userThingBeanList.size() > 13 ? "+" + String.valueOf(userThingBeanList.size()) + "人赞" : String.valueOf(userThingBeanList.size() + "人赞"));
            approveList.updateApproveList(thingPhotoList);
        }
    }

    /**
     * 该动态不存在
     */
    @Override
    public void showDynamicNotExist() {
        showShortText("该动态已被作者删除");
        finish();
    }

    @Override
    public void showFollowed(FollowBean followBean) {
        if (followBean.getCode() == 0) {
            //未关注
            tvAttention.setText("关注");
            tvAttention.setCompoundDrawablesWithIntrinsicBounds(attention, null, null, null);
        } else if (followBean.getCode() == 1) {
            //已关注
            tvAttention.setText("已关注");
            tvAttention.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    private void showDynamicMenu(Context context, int position, final DynamicDetailBean.DataBean.CommentBean bean) {
        mPosition = position;
        ActionSheet actionSheet = new ActionSheet(context);
        if (bean.getUid().equals(uid) && !isFinishing()) {
            actionSheet.builder()
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    .addSheetItem("删除", ActionSheet.SheetItemColor.Blue, new ActionSheet.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            switch (which) {
                                case 1:
                                    CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                                            "确定要删除这条评论么？",
                                            new CustomDialog.OnCloseListener() {
                                                @Override
                                                public void onClick(Dialog dialog, boolean confirm) {
                                                    if (confirm) {
                                                        LogUtils.i(bean.getId(), "删除评论的ID：");
                                                        mPresenter.deleteComment(uid, bean.getId(), mDynamicId, mPosition, dynamicPosition);
                                                        dialog.dismiss();
                                                    } else {
                                                        dialog.dismiss();
                                                    }
                                                }
                                            }).setTitle("提示");
                                    dialog.setCanceledOnTouchOutside(true);
                                    dialog.show();
                                    break;
                                default:
                            }
                        }
                    })
                    .show();
        }
    }

    @Override
    public boolean isFinishing() {
        return super.isFinishing();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initEmotionMainFragment();
    }
}
